package com.zengqingfa.thread.orderthread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @fileName: CycleBarrierTest2
 * @author: zengqf3
 * @date: 2021-6-26 13:42
 * @description:
 */
public class CycleBarrierTest3 {
    static CyclicBarrier barrier = new CyclicBarrier(5);

    /**
     * pool-1-thread-1:到达栅栏
     * pool-1-thread-4:到达栅栏
     * pool-1-thread-3:到达栅栏
     * pool-1-thread-5:到达栅栏
     * pool-1-thread-2:到达栅栏
     * pool-1-thread-2:穿过栅栏
     * pool-1-thread-4:穿过栅栏
     * pool-1-thread-4:执行任务
     * pool-1-thread-1:穿过栅栏
     * pool-1-thread-1:执行任务
     * pool-1-thread-5:穿过栅栏
     * pool-1-thread-5:执行任务
     * pool-1-thread-3:穿过栅栏
     * pool-1-thread-3:执行任务
     * pool-1-thread-2:执行任务
     *
     * @param args
     */
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        //线程已经到达栅栏
                        System.out.println(Thread.currentThread().getName() + ":" + "到达栅栏");
                        barrier.await();
                        System.out.println(Thread.currentThread().getName() + ":" + "穿过栅栏");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ":" + "执行任务");
                }
            };
            executorService.submit(runnable);
        }
    }
}
